<template>
	<view class="container">
		<!-- 横幅区域 -->
		<view class="banner">
			<view class="banner-bg">
				<text class="banner-text">智能维护系统</text>
			</view>
		</view>
		
		<!-- 主要功能按钮（按截图仅保留三项） -->
		<view class="main-actions">
			<!-- 1. 添加报修 -->
			<view class="action-item" @click="goToAddRepair">
				<view class="action-icon orange">
					<text class="icon-text">➕</text>
				</view>
				<text class="action-title">添加报修</text>
			</view>
			
			<!-- 2. 我的报修 -->
			<view class="action-item" @click="goToMyReports">
				<view class="action-icon red">
					<text class="icon-text">📋</text>
					<view class="badge" v-if="getBadgeCount('fault-report') > 0">{{ getBadgeCount('fault-report') }}</view>
				</view>
				<text class="action-title">我的报修</text>
			</view>
			
			<!-- 3. 我的维修 -->
			<view class="action-item" @click="goToRepairs">
				<view class="action-icon green">
					<text class="icon-text">🛠️</text>
					<view class="badge" v-if="getBadgeCount('repairs') > 0">{{ getBadgeCount('repairs') }}</view>
				</view>
				<text class="action-title">我的维修</text>
			</view>

			<!-- 4. 备件管理 -->
			<view class="action-item" @click="goToSpareParts">
				<view class="action-icon teal">
					<text class="icon-text">🧰</text>
				</view>
				<text class="action-title">备件管理</text>
			</view>
		</view>
		
		
		
		
		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view
				v-for="(item, index) in menuItems"
				:key="item.key"
				:class="['nav-item', { active: index === 0 }]"
				@click="navigateToMenuItem(item)"
			>
				<text class="nav-icon">{{ item.icon }}</text>
				<text class="nav-text">{{ item.name }}</text>
				<view class="nav-badge" v-if="getBadgeCount(item.key) > 0">{{ getBadgeCount(item.key) }}</view>
			</view>
		</view>
	</view>
</template>

<script>
		import permissionManager from '@/utils/permission.js'
		import PermissionCheck from '@/components/PermissionCheck.vue'
		import navigation from '@/utils/navigation.js'
		import { getUserInfo } from '@/utils/auth'
		import { listWorkOrder } from '@/api/repair/workOrder'
		import { listFaultReport } from '@/api/repair/faultReport'
		import assetApi from '@/api/asset/asset'
	
	export default {
		components: {
			PermissionCheck
		},
		data() {
			return {
				title: '智慧维保工作台',
				userInfo: {},
				roleConfig: null,
				menuItems: [],
				permissionManager: permissionManager,
				statistics: {
					totalDevices: 0,
					normalDevices: 0,
					faultDevices: 0,
					idleDevices: 0,
					scrappedDevices: 0,
					maintenanceDevices: 0
				}
			}
		},
		onLoad() {
			this.checkLoginStatus();
		},
		onShow() {
			this.loadUserInfo();
			// 确保用户信息加载后再加载角色配置
			this.$nextTick(() => {
				this.loadRoleConfig();
				this.checkPageAccess();
				this.loadAssetStatistics();
			});
		},
		methods: {
		// 检查登录状态
		checkLoginStatus() {
			const { isLoggedIn } = require('@/utils/auth');
			if (!isLoggedIn()) {
				// 未登录，跳转到登录页
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		},
		
			// 加载用户信息
			loadUserInfo() {
				const { getUserInfo } = require('@/utils/auth');
				const userInfo = getUserInfo();
				if (userInfo) {
					this.userInfo = userInfo;
					// 设置权限管理器
					permissionManager.setUserInfo(userInfo);
				}
			},
			
			// 检查页面访问权限
			checkPageAccess() {
				// 如果是维修人员访问工作台页面，应该重定向到他们的首页
				if (permissionManager.isMaintenanceWorker()) {
					console.log('维修人员访问工作台，检查是否需要重定向...');

					// 检查工作台是否在维修人员的菜单项中
					const hasDashboardAccess = this.menuItems.some(item => item.path === '/pages/index/index');

					if (!hasDashboardAccess) {
						console.log('维修人员无权访问工作台，重定向到首页');
						const roleHomePage = permissionManager.getRoleHomePage();
						uni.reLaunch({
							url: roleHomePage
						});
						return;
					}
				}
			},

			// 加载角色配置
			loadRoleConfig() {
				console.log('开始加载角色配置...');
				console.log('当前用户信息:', this.userInfo);

				this.roleConfig = permissionManager.getRoleConfig();
				this.menuItems = permissionManager.getMenuItems() || [];

				console.log('角色配置:', this.roleConfig);
				console.log('菜单项:', this.menuItems);
				console.log('用户角色:', this.userInfo.roles);
				console.log('角色键:', permissionManager.getRoleKey());
				console.log('是否有admin角色:', permissionManager.hasRole('admin'));

				// 检查是否应该重定向到角色特定页面
				if (permissionManager.shouldRedirectToRolePage()) {
					const roleHomePage = permissionManager.getRoleHomePage();
					console.log('重定向到角色特定首页:', roleHomePage);

					// 延迟一点时间，确保页面完全加载后再重定向
					setTimeout(() => {
						uni.reLaunch({
							url: roleHomePage
						});
					}, 500);
					return; // 提前返回，避免继续执行
				}

				// 如果没有菜单项，设置默认菜单项
				if (!this.menuItems || this.menuItems.length === 0) {
					console.log('没有菜单项，设置默认菜单');
					this.menuItems = [
						{ key: 'dashboard', name: '工作台', icon: '📊', path: '/pages/index/index' },
						{ key: 'fault-report', name: '故障报修', icon: '📝', path: '/pages/repair/fault-report' },
						{ key: 'test', name: '测试功能', icon: '🧪', path: '/pages/test/simple-test' }
					];
				}
			},
			
			// 获取头部样式
			getHeaderStyle() {
				if (!this.roleConfig) return {};
				const themeStyles = permissionManager.getThemeStyles();
				return {
					'background': `linear-gradient(135deg, ${themeStyles['--primary-color']}, ${themeStyles['--secondary-color']})`
				};
			},
			
			// 获取功能项样式
			getActionItemStyle() {
				if (!this.roleConfig) return {};
				return {
					'border-color': this.roleConfig.primaryColor
				};
			},
			
			// 获取功能图标样式类
			getActionIconClass(key) {
				const colorMap = {
					'dashboard': 'blue',
					'assets': 'green',
					'repairs': 'orange',
					'fault-report': 'red',
					'spare-parts': 'teal',
					'reports': 'purple',
					'system': 'gray'
				};
				return colorMap[key] || 'blue';
			},
			
			// 获取徽章数量
			getBadgeCount(key) {
				try {
					switch (key) {
						case 'repairs':
							// 维修任务数量根据用户角色决定
							if (permissionManager.isMaintenanceWorker()) {
								// 维修人员：返回分配给他们的所有任务数量
								return this.getWorkerTaskCount()
							} else {
								// 管理员：返回所有待分配的任务数量
								return this.getPendingTaskCount()
							}

						case 'fault-report':
							// 故障报修数量 - 维修人员不需要显示数量
							return 0

						default:
							return 0
					}
				} catch (error) {
					console.error('获取徽章数量失败:', error)
					return 0
				}
			},

			// 获取维修人员任务数量（分配给他们的所有任务）
			async getWorkerTaskCount() {
				try {
					const userInfo = getUserInfo()
					if (!userInfo?.user?.userId) return 0

					const res = await listWorkOrder({
						assigneeId: userInfo.user.userId,
						status: 'PENDING_ASSIGN,ASSIGNED,PENDING_EXEC,IN_PROGRESS,WAITING_MATERIAL,PENDING_CONFIRM'
					})

					return res?.rows?.length || 0
				} catch (error) {
					console.error('获取维修人员任务数量失败:', error)
					return 0
				}
			},

			// 获取待分配任务数量
			async getPendingTaskCount() {
				try {
					const res = await listWorkOrder({
						status: 'PENDING_ASSIGN'
					})

					return res?.rows?.length || 0
				} catch (error) {
					console.error('获取待分配任务数量失败:', error)
					return 0
				}
			},

			// 获取自己报修的故障单数量
			async getMyFaultReportCount() {
				// 维修人员暂时不显示故障报修数量，避免权限问题
				// 如果需要显示，可以在后端添加相应的权限控制
				return 0
			},
			
			// 导航到页面
			navigateToPage(path) {
				if (path) {
					uni.navigateTo({
						url: path
					});
				} else {
					uni.showToast({
						title: '功能开发中',
						icon: 'none'
					});
				}
			},
			
			
			goToProfile() {
				uni.navigateTo({
					url: '/pages/user/profile'
				});
			},
			
			
			// 新增：按截图的三个入口
			goToAddRepair() {
				uni.navigateTo({
					url: '/pages/repair/add'
				});
			},
			
			goToMyReports() {
				uni.navigateTo({
					url: '/pages/repair/records'
				});
			},
			
			// 功能按钮点击事件 - 使用智能导航
			goToFaultReport() {
				navigation.goToFaultReport();
			},
			
			goToRepairs() {
				navigation.goToRepairs();
			},
			
			goToAssetManagement() {
				navigation.goToAssetManagement();
			},
			
			goToSpareParts() {
				uni.navigateTo({
					url: '/pages/spare-parts/index'
				});
			},
			
			goToReports() {
				uni.showToast({
					title: '统计报表功能开发中',
					icon: 'none'
				});
			},
			
			goToSystemSettings() {
				uni.showToast({
					title: '系统设置功能开发中',
					icon: 'none'
				});
			},
			
			goToMore() {
				navigation.goToMore();
			},
			
			// 导航到菜单项
			navigateToMenuItem(item) {
				if (item && item.path) {
					console.log('导航到菜单项:', item);
					// 使用智能导航，保持与其他页面一致的滑动切换效果
					navigation.smartNavigate(item.path);
				} else {
					uni.showToast({
						title: '功能开发中',
						icon: 'none'
					});
				}
			},
			
			// 加载资产统计数据
			async loadAssetStatistics() {
				try {
					console.log('开始加载资产统计数据...');
					const res = await assetApi.getAssetStatistics();
					console.log('资产统计数据响应:', res);
					
					if (res && res.code === 200) {
						const data = res.data || res;
						this.statistics = {
							totalDevices: data.total || data.totalDevices || 0,
							normalDevices: data.normal || data.normalDevices || 0,
							faultDevices: data.fault || data.faultDevices || 0,
							idleDevices: data.idle || data.idleDevices || 0,
							scrappedDevices: data.scrapped || data.scrappedDevices || 0,
							maintenanceDevices: data.maintenance || data.maintenanceDevices || 0
						};
						console.log('资产统计数据加载成功:', this.statistics);
					} else {
						console.log('资产统计数据加载失败，使用默认值');
					}
				} catch (error) {
					console.error('加载资产统计数据失败:', error);
					// 保持默认值，不显示错误提示
				}
			}
		}
	}
</script>

<style>
	.container {
		background-color: #ffffff;
		min-height: 100vh;
		padding-bottom: 160rpx;
	}
	
	/* 横幅区域 */
	.banner {
		position: relative;
		height: 300rpx;
		margin: 20rpx 30rpx;
		border-radius: 20rpx;
		overflow: hidden;
	}
	
	.banner-bg {
		width: 100%;
		height: 100%;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.banner-text {
		color: #ffffff;
		font-size: 36rpx;
		font-weight: bold;
	}
	
	/* 统计卡片样式 */
	.statistics-card {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin: 20rpx 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}
	
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.card-title {
		display: flex;
		align-items: center;
	}
	
	.title-icon {
		font-size: 32rpx;
		margin-right: 15rpx;
	}
	
	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.arrow-icon {
		font-size: 28rpx;
		color: #999;
	}
	
	.statistics-grid {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 30rpx;
	}
	
	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
	}
	
	.stat-number {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.stat-number.normal {
		color: #4caf50;
	}
	
	.stat-number.fault {
		color: #f44336;
	}
	
	.stat-label {
		font-size: 24rpx;
		color: #666;
	}
	
	/* 主要功能按钮 */
	.main-actions {
		display: flex;
		justify-content: space-around;
		padding: 40rpx 30rpx;
		background-color: #ffffff;
	}
	
	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
	}
	
	.action-icon {
		position: relative;
		width: 120rpx;
		height: 120rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.action-icon.orange {
		background-color: #ff9800;
	}
	
	.action-icon.red {
		background-color: #f44336;
	}
	
	.action-icon.green {
		background-color: #4caf50;
	}

	.action-icon.teal {
		background-color: #20b2aa;
	}
	
	.icon-text {
		font-size: 48rpx;
		color: #ffffff;
	}
	
	.badge {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		background-color: #ff4444;
		color: #ffffff;
		font-size: 20rpx;
		padding: 4rpx 8rpx;
		border-radius: 20rpx;
		min-width: 30rpx;
		text-align: center;
	}
	
	.action-title {
		font-size: 24rpx;
		color: #333333;
		text-align: center;
	}
	

	
	
	.test-actions {
		display: flex;
		gap: 20rpx;
		margin: 20rpx 30rpx;
	}
	
	.test-btn {
		flex: 1;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #17a2b8;
		color: white;
		border: none;
		border-radius: 8rpx;
		font-size: 24rpx;
		text-align: center;
	}
	
	/* 底部导航栏 */
	.bottom-nav {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 1rpx solid #e0e0e0;
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0;
		z-index: 9999;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
		height: 120rpx;
	}
	
	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
		position: relative;
		flex: 1;
		color: #999999;
		font-size: 24rpx;
		padding: 10rpx 0;
	}
	
	.nav-item.active {
		color: #007AFF;
	}
	
	.nav-item.active .nav-icon {
		color: #007AFF;
	}
	
	.nav-item.active .nav-text {
		color: #007AFF;
		font-weight: 500;
	}
	
	.nav-icon {
		font-size: 40rpx;
		margin-bottom: 5rpx;
		color: #666666;
	}
	
	.nav-text {
		font-size: 20rpx;
		color: #666666;
	}
	
	.nav-badge {
		position: absolute;
		top: 5rpx;
		right: 15rpx;
		width: 20rpx;
		height: 20rpx;
		background-color: #ff3b30;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12rpx;
		color: white;
		font-weight: bold;
		min-width: 20rpx;
		text-align: center;
		line-height: 1;
	}
	
</style>